package logic.common.game;

import java.util.ArrayList;
import java.util.List;

import com.jme.math.FastMath;

import logic.common.team.Team;
import map.spawnStation.SpawnStation;
import map.spawnStation.stationListeners.ConquerHelpedEvent;
import map.spawnStation.stationListeners.SpawnStationListener;
import map.spawnStation.stationListeners.StationConqueredEvent;
import gameStates.absGamesStates.AbsIngameState;

public class TicketsDegrader {
	
	private Game game;
	private AbsIngameState ingameState;
	private List<TicketsDegradingController> controllers;
	
	public TicketsDegrader(Game game, AbsIngameState ingameState) {
		this.game = game;
		this.ingameState = ingameState;
		
		controllers = new ArrayList<TicketsDegradingController>();
		
		for(SpawnStation station : game.getMap().getSpawnStations()) {
			station.addSpawnStationListener(getNewStationListener());
		}
	}
	
	private SpawnStationListener getNewStationListener() {
		return new SpawnStationListener() {
			@Override
			public void conquered(StationConqueredEvent event) {
				checkStations();
			}
			
			@Override
			public void stationNeutralized() {
				checkStations();
			}
			
			@Override
			public void helpedConquer(ConquerHelpedEvent event) {}
		};
	}
	
	private void checkStations() {
		Team teamA = game.getTeamA();
		Team teamB = game.getTeamB();
		int stationsA = teamA.getSpawnStations().size();
		int stationsB = teamB.getSpawnStations().size();
		
		clearControllers();
		if(stationsA != stationsB) {
			int diff = stationsA - stationsB;
			
			if(diff > 0) {
				addControllers(diff, teamB);
			} else {
				addControllers(-diff, teamA);
			}
			
			assert(controllers.size() == (int)FastMath.abs(diff));
		}
	}
	
	private void clearControllers() {
		for(TicketsDegradingController c : controllers) {
			ingameState.getRootNode().removeController(c);
		}
		
		controllers.clear();
	}
	
	private void addControllers(int amount, Team team) {
		assert(amount > 0);
				
		for(int i = 0; i < amount; i++) {
			TicketsDegradingController c = new TicketsDegradingController(team);
			ingameState.getRootNode().addController(c);
			controllers.add(c);
		}
	}
}